package org.sunrise.game.center.client;

import lombok.Getter;
import lombok.Setter;
import org.sunrise.game.common.network.client.BaseClient;
import org.sunrise.game.common.network.client.BaseClientManager;

@Getter
@Setter
public class ReportClient {
    private final BaseClient connectToCenter;
    private String clientIp; //当前节点上报ip
    private int clientPort; //当前节点上报port
    private int type; //节点类型
    private int serverId; //服务id

    private String masterIp;
    private int masterPort;

    public ReportClient(String nodeId, int type) {
        this.type = type;
        this.connectToCenter = new BaseClient(nodeId) {
            @Override
            public void onFail() {
                super.onFail();
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                connectMaster(masterIp, masterPort);
            }
        };
        ReportClientMessageManager messageManager = new ReportClientMessageManager(connectToCenter.getNodeId());
        this.connectToCenter.setClientHandler(r -> new ReportClientHandler(nodeId));
        this.connectToCenter.setMessageManager(messageManager);
        BaseClientManager.register(connectToCenter);
    }

    public ReportClient(String nodeId, int type, int serverId, String clientIp, int clientPort) {
        this.type = type;
        this.clientIp = clientIp;
        this.clientPort = clientPort;
        this.serverId = serverId;
        this.connectToCenter = new BaseClient(nodeId) {
            @Override
            public void onFail() {
                super.onFail();
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                connectMaster(masterIp, masterPort);
            }
        };
        ReportClientMessageManager messageManager = new ReportClientMessageManager(connectToCenter.getNodeId());
        this.connectToCenter.setClientHandler(r -> new ReportClientHandler(nodeId));
        this.connectToCenter.setMessageManager(messageManager);
        BaseClientManager.register(connectToCenter);
    }

    public void connectMaster(String ip, int port) {
        masterIp = ip;
        masterPort = port;
        connectToCenter.connect(ip, port);
    }

    public void reConnectMaster() {
        connectToCenter.connect(masterIp, masterPort);
    }
}
